package com.gaobug.platform.mq;

import cn.hutool.core.io.FileUtil;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.gaobug.base.config.mq.RabbitMqProperties;
import com.gaobug.base.utils.email.MailSendInfo;
import com.gaobug.base.utils.email.SendMailUtils;
import com.gaobug.base.utils.file.FileUtils;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.*;

/**
 * 邮件消费
 *
 * @author gaobug
 */
@Slf4j
@Component
@ConditionalOnProperty(prefix = RabbitMqProperties.PREFIX, name = "enable", havingValue = "true")
public class EmailListen {
    @Resource
    private SendMailUtils sendMailUtils;

    @RabbitListener(queues = "#{rabbitMqFactory.queueConfigMap['email'].queueName}")
    @Transactional(rollbackFor = Exception.class)
    public void receiveMessage(Channel channel, Message message) throws IOException {
        try {
            String msg = new String(message.getBody());
            MailSendInfo mailSendInfo = JacksonUtils.toObj(msg, MailSendInfo.class);
            sendMailUtils.sendEmail(mailSendInfo.getSubject(), mailSendInfo.getReceiver(), mailSendInfo.getContext());
            log.info("邮件发送成功");
            // 消费确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
        } catch (Exception exception) {
            exception.printStackTrace();
            // 消费失败异常，异常放入死信队列
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        }
    }
}
